<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="基准值生效时间" prop="recordTime">
        <el-date-picker
          v-model="formData.recordTime"
          type="date"
          value-format="x"
          placeholder="选择基准值生效时间"
        />
      </el-form-item>
      <el-form-item label="心率基准值（次/分）" prop="heartRate">
        <el-input v-model="formData.heartRate" placeholder="请输入心率基准值（次/分）" />
      </el-form-item>
      <el-form-item label="收缩压基准值（mmHg）" prop="systolicPressure">
        <el-input v-model="formData.systolicPressure" placeholder="请输入收缩压基准值（mmHg）" />
      </el-form-item>
      <el-form-item label="舒张压基准值（mmHg）" prop="diastolicPressure">
        <el-input v-model="formData.diastolicPressure" placeholder="请输入舒张压基准值（mmHg）" />
      </el-form-item>
      <el-form-item label="血氧饱和度基准值（%）" prop="oxygenSaturation">
        <el-input v-model="formData.oxygenSaturation" placeholder="请输入血氧饱和度基准值（%）" />
      </el-form-item>
      <el-form-item label="压力指数基准值（HRV分）" prop="stress">
        <el-input v-model="formData.stress" placeholder="请输入压力指数基准值（HRV分）" />
      </el-form-item>
      <el-form-item label="心梗指数1" prop="richSore1">
        <el-input v-model="formData.richSore1" placeholder="请输入心梗指数1" />
      </el-form-item>
      <el-form-item label="心梗指数2" prop="richSore2">
        <el-input v-model="formData.richSore2" placeholder="请输入心梗指数2" />
      </el-form-item>
      <el-form-item label="反应时间基准值（毫秒）" prop="reactionTime">
        <el-date-picker
          v-model="formData.reactionTime"
          type="date"
          value-format="x"
          placeholder="选择反应时间基准值（毫秒）"
        />
      </el-form-item>
      <el-form-item label="男性握力基准值（kg）" prop="gripStrength">
        <el-input v-model="formData.gripStrength" placeholder="请输入男性握力基准值（kg）" />
      </el-form-item>
      <el-form-item label="男性肺活量基准值（mL）" prop="vitalCapacity">
        <el-input v-model="formData.vitalCapacity" placeholder="请输入男性肺活量基准值（mL）" />
      </el-form-item>
      <el-form-item label="呼气酒精含量基准值（mg/L）" prop="breathAlcohol">
        <el-input v-model="formData.breathAlcohol" placeholder="请输入呼气酒精含量基准值（mg/L）" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { StandardApi, StandardVO } from '@/api/health/standard'

/** 存储健康指标基准值，上下限通过计算规则动态生成 表单 */
defineOptions({ name: 'StandardForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  recordTime: undefined,
  heartRate: undefined,
  systolicPressure: undefined,
  diastolicPressure: undefined,
  oxygenSaturation: undefined,
  stress: undefined,
  richSore1: undefined,
  richSore2: undefined,
  reactionTime: undefined,
  gripStrength: undefined,
  vitalCapacity: undefined,
  breathAlcohol: undefined,
})
const formRules = reactive({
  recordTime: [{ required: true, message: '基准值生效时间不能为空', trigger: 'blur' }],
  heartRate: [{ required: true, message: '心率基准值（次/分）不能为空', trigger: 'blur' }],
  systolicPressure: [{ required: true, message: '收缩压基准值（mmHg）不能为空', trigger: 'blur' }],
  diastolicPressure: [{ required: true, message: '舒张压基准值（mmHg）不能为空', trigger: 'blur' }],
  oxygenSaturation: [{ required: true, message: '血氧饱和度基准值（%）不能为空', trigger: 'blur' }],
  stress: [{ required: true, message: '压力指数基准值（HRV分）不能为空', trigger: 'blur' }],
  richSore1: [{ required: true, message: '心梗指数1不能为空', trigger: 'blur' }],
  richSore2: [{ required: true, message: '心梗指数2不能为空', trigger: 'blur' }],
  reactionTime: [{ required: true, message: '反应时间基准值（毫秒）不能为空', trigger: 'blur' }],
  gripStrength: [{ required: true, message: '男性握力基准值（kg）不能为空', trigger: 'blur' }],
  vitalCapacity: [{ required: true, message: '男性肺活量基准值（mL）不能为空', trigger: 'blur' }],
  breathAlcohol: [{ required: true, message: '呼气酒精含量基准值（mg/L）不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await StandardApi.getStandard(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as StandardVO
    if (formType.value === 'create') {
      await StandardApi.createStandard(data)
      message.success(t('common.createSuccess'))
    } else {
      await StandardApi.updateStandard(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    recordTime: undefined,
    heartRate: undefined,
    systolicPressure: undefined,
    diastolicPressure: undefined,
    oxygenSaturation: undefined,
    stress: undefined,
    richSore1: undefined,
    richSore2: undefined,
    reactionTime: undefined,
    gripStrength: undefined,
    vitalCapacity: undefined,
    breathAlcohol: undefined,
  }
  formRef.value?.resetFields()
}
</script>